import { utils, writeFile } from 'xlsx-js-style'

function withStyle (list) {
  const item = list[0]
  if (!item) return []
  if (!Array.isArray(item)) {
    list = [list]
  }
  return list.map(v => {
    return v.map(vv => ({
      v: vv,
      s: {
        border: {
          top: { style: 'thin' },
          right: { style: 'thin' },
          bottom: { style: 'thin' },
          left: { style: 'thin' },
        }
      }
    }))
  })
}

/**
 * 导出数据 对象数组转excel文件
 * @param fileName {String}
 * @param headers {Array<String>}
 * @param data {Array<Object>}
 * @param sheetName {String}
 */
export function simpleJson2Sheet (fileName, headers, data, sheetName = 'sheet1') {
  const worksheet = utils.json_to_sheet(data)
  const workbook = utils.book_new()
  utils.book_append_sheet(workbook, worksheet, sheetName)
  utils.sheet_add_aoa(worksheet, headers, { origin: 'A1' })

  try {
    const row = data[0]
    const keys = Object.keys(row)
    worksheet['!cols'] = keys.map(key => ({ wch: data.reduce((w, r) => Math.max(w, String(r[key]).length), 15) }))
  } catch (e) {}

  writeFile(workbook, fileName, { compression: true })
}

/**
 * 导出数据 将页面table表格导出为excel文件
 * @param elem{element | string}
 * @param fileName{string}
 * @param title{string}
 */
export function simpleTable2Sheet (elem, fileName, title = 'Sheet1') {
  const table = typeof elem === 'string' ? document.getElementById('elem') : elem
  const worksheet = utils.table_to_sheet(table)
  const workbook = utils.book_new()
  utils.book_append_sheet(workbook, worksheet, title)

  writeFile(workbook, fileName);
}

/**
 * 导出数据 将aoa导出为excel文件
 * @param aoa{[]}
 * @param fileName{string}
 * @param sheetName{string}
 */
export function simpleAoa2Sheet (aoa, fileName, sheetName = 'Sheet1') {
  const aoaWithStyle = withStyle(aoa)
  const worksheet = utils.aoa_to_sheet(aoaWithStyle)
  const workbook = utils.book_new()
  utils.book_append_sheet(workbook, worksheet, sheetName)


  try {
    const row = aoa[0]
    const keys = Object.keys(row)
    worksheet['!cols'] = keys.map((v, i) => ({ wch: aoa.reduce((w, r) => Math.max(w, String(r[i]).length), 0) * 2 + 8 }))
    // console.log(worksheet['!cols'])
  } catch (e) {}

  writeFile(workbook, fileName)
}
